package redis.client.nedis;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author gaodong
 * @version 1.0
 * @date 2020/11/19 10:51
 */
public class TestCls {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        final EventLoopGroup bossGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());
        final Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(bossGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .remoteAddress("127.0.0.1", 6379)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) {
                    }
                });

        ChannelFuture cf = bootstrap.connect().sync();
        cf.get();
        System.out.println("connect success");

        for (int i = 0; i < 10; i++) {

            long s = System.nanoTime();

            ChannelFuture ncf = cf.channel().write(Unpooled.copiedBuffer("*2\r\n$3\r\nGET\r\b$1\r\na\r\n", CharsetUtil.UTF_8));
            cf.channel().flush();

            ncf.addListener(new GenericFutureListener<Future<? super Void>>() {
                @Override
                public void operationComplete(Future<? super Void> future) throws Exception {
                    System.out.println("async done");
                }
            });
            ncf.awaitUninterruptibly(10, TimeUnit.SECONDS);

            System.out.println("sync done");

            System.out.println(ncf.isSuccess());

            long e = System.nanoTime();
            System.out.println((e - s) / 1e6 + "ms");
            System.out.println();
        }
    }
}
